import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:enterprise_v8/app/components/custom_web_page.dart';
import 'package:enterprise_v8/app/components/toast_widget.dart';
import 'package:enterprise_v8/app/core/core.dart';
import 'package:enterprise_v8/app/core/ext/assets.dart';
import 'package:enterprise_v8/app/core/ext/ext.dart';
import 'package:enterprise_v8/app/core/ext/time.dart';
import 'package:enterprise_v8/app/core/utils/scan_util.dart';
import 'package:enterprise_v8/app/core/utils/user_manager.dart';
import 'package:enterprise_v8/app/data/api/auth_apis.dart';
import 'package:enterprise_v8/app/data/entities/auth/user_login_entity.dart';
import 'package:enterprise_v8/modules/home/home_page/home_page_control.dart';
import 'package:enterprise_v8/modules/home/message/message_control.dart';
import 'package:enterprise_v8/modules/home/workbench/workbench_control.dart';
import 'package:enterprise_v8/router/app_pages.dart';

class UserControl extends GetxController {
  /// 当点击切换用户
  void onTapSwitchUser() {
    final panel = StatefulBuilder(builder: (_, setState) {
      final items = UserManager.getLoginCredentialList(includeThis: false);
      if (items.isEmpty) {
        return [
          Text('切换用户', style: TextStyles.bold23),
          const Spacer(),
          Center(
            child: [
              const Text('没有可切换的用户'),
              AppGaps.vGap10,
              ElevatedButton(
                  onPressed: () {
                    UserManager.removeUserInfo();
                    Get.offNamedUntil(
                      Routes.authLogin,
                      (route) => false,
                    );
                  },
                  child: const Text('新增用户')),
            ].toColumn(
              mainAxisAlignment: MainAxisAlignment.center,
            ),
          ),
          const Spacer(),
        ].toColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
        );
      }
      final accounts = items
          .map(
            (e) => Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(17.w),
              ),
              child: ListTile(
                leading: 'https://scpic.chinaz.net/files/pic/pic9/202207/apic42382.jpg'.asImg(
                  fit: BoxFit.cover,
                  radius: 7.w,
                  width: 47.w,
                  height: 47.w,
                ),
                title: Text(e.nickName ?? e.userName),
                subtitle: e.lastLogin != null
                    ? Text(
                        '上次登录：${e.lastLogin?.toAgo}',
                        style: TextStyles.grey_14,
                      )
                    : null,
                trailing: IconButton(
                  icon: const Icon(Icons.delete),
                  onPressed: () {
                    UserManager.removeLoginCredential(e.userName);
                    setState(() {});
                  },
                ),
                onTap: () async {
                  Get.back();
                  SmartDialog.showLoading();
                  try {
                    _onSwitchUser(e);
                  } catch (e) {
                    AppToast.showError('切换用户失败');
                  } finally {
                    SmartDialog.dismiss();
                  }
                },
              ),
            ),
          )
          .joinWith(AppGaps.vGap10);
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('切换用户', style: TextStyles.bold23),
          AppGaps.vGap20,
          ...accounts,
        ],
      );
    });
    panel.paddingAll(17.w).showBottomSheetDialog();
  }

  void _onSwitchUser(UserLoginEntity e) async {
    UserManager.removeToken();
    final result = await AuthApis.login(
      username: e.userName,
      password: e.passWord,
    ).execute();

    if (result.data != null) {
      UserManager.saveUser(result.data!);
      UserManager.saveToken(
        '${result.data!.tokenType} ${result.data!.accessToken}',
      );
    } else {
      AppToast.showError('用户数据为空');
    }
    update();
    try {
      Get.find<MessageControl>().update();
      Get.find<HomePageControl>().update();
      Get.find<WorkbenchControl>().update();
    } catch (e) {
      /// 如果刷新其他页面的数据失败，就退出登录
      AppToast.showError('切换用户失败');
      UserManager.logout();
    }
  }

  /// 扫描
  Future<void> onTapScan() async {
    final String data = await ScanUtil.scanQROrBarCode();
    if (data.isEmpty) {
      return;
    }
    // todo 如果带有enterprise_v8(待和后端沟通)跳转到确认登录页面
    if (true) {
      Get.toNamed(Routes.personalScanLogin);
      return;
    }
    // 如果带有http就跳转到web页面
    if (data.contains('http')) {
      Get.to(CustomWbePage(url: data));
      return;
    }
    AppToast.showWarning('请扫描正确二维码');
  }

  /// 点击版本信息
  void onTapVersion() {
    Get.toNamed(Routes.personalVersionInfo);
  }

  /// 点击帮助
  void onTapHelp() {
    Get.toNamed(Routes.personalHelp);
  }

  /// 点击设置
  void onTapSetting() {
    Get.toNamed(Routes.personalSetting);
  }
}
